var ProductListData;
var itemPerPage = 10;
$(document).ready(function(){
	loadTable("","");
	$("#btn_search").click($.fn.SEARCH_RESULT);
	$("#btn_add").click($.fn.GO_UPDATE);
	$(".act_icon_view").click($.fn.SHOW_IMG);
	$( "#dialog-message" ).dialog({
		modal: true,
		autoOpen: false,
		buttons: {
			'ok': function() {
				$( this ).dialog( "close" );
			}
		}
	});
});

$.fn.SHOW_IMG = function() {
	var index = $(this).attr('key_id');
	$("#show_img").show();
	$("#show_img").attr('src','HomeServlet?action=GETIMG&newletter_Id='+index);
	
};

$.fn.GO_UPDATE = function (){
	if($(this).attr('action_goto') == 'EDIT'){
		getEditData($(this).attr('key_id'));
	}
	$("#hidden_product_code").val($(this).attr('key_id'));
	$("#action_to_update").val($(this).attr('action_goto'));
	var action = $("#search_frm").attr('action');
	$( "#dialog-data_section" ).dialog({
		modal: true,
		width: 600,
		height:400,
		buttons: {
			'submit': function() {
				$( this ).dialog( "close" );
				$( '#data_section' )
				  .submit( function( e ) {
				    $.ajax( {
				      url: action,
				      type: 'POST',
				      data: new FormData( this ),
				      processData: false,
				      contentType: false
				    } );
				    e.preventDefault();
				  } );
			},
			'cancel': function(e) {
				$('#data_section')[0].reset();
				$(".show_img").attr('src','');
				$(".show_img").hide();
				$( this ).dialog( "close" );
			}
		}
	});
};

$.fn.GO_DELETE = function(){
	
	var productId = $(this).attr('key_id');
	var action = $("#search_frm").attr('action');
	$( "#dialog-message-confirm_delete" ).dialog({
		modal: true,
		buttons: {
			'delete': function() {
				$( this ).dialog( "close" );
				$.ajax({
					 type: "POST",
					 url: action,
					 data: {
						 productId : productId,
						 action : "DELETE"
						 },
					 dataType: "json",
					 success: function(data){
						 if(data[data.length - 1]){
							 loadTable("","");
						 } else {
							 $("#p_freetext").html('Cannot delete this item!');
							 $( "#dialog-message" ).dialog('open');
						 }
					 },
					error : function(xhr, ajaxOptions, thrownError) {
						$("#p_freetext").html('Error while processing '+xhr+" :: "+thrownError);
						 $( "#dialog-message" ).dialog('open');
					}
				});
			},
			'cancel': function() {
				$( this ).dialog( "close" );
			}
		}
	});
};

$.fn.SEARCH_RESULT = function() {
	loadTable($("#srh_product_name").val(), $("#srh_supplier_name").val());
};

function loadTable(productName, supplierName){
	var datas = $("#search_frm").serializeArray();
	var action = $("#search_frm").attr('action');
	$.ajax({
		 type: "POST",
		 url: action,
		 data: datas,
		 dataType: "json",
		 success: function(data){
			 ProductListData = data;
			 var tableLayout = genTable(data, 1);
			 $("#dataTbody").html(tableLayout);
			 $(".act_icon_edit").click($.fn.GO_UPDATE);
			 $(".act_icon_delete").click($.fn.GO_DELETE);
		 },
		error : function(xhr, ajaxOptions, thrownError) {
			alert("Error while processing.");
		}
	});
}

function genTable(data, pages){
	var totalRecords = data.length;
	var maxPage = Math.ceil(totalRecords / itemPerPage);
	var i = 0;
	var loops = totalRecords;
	if(pages > 1){
		i = ((parseInt(pages) * itemPerPage) - itemPerPage);
	}
	if(maxPage > pages){
		loops = i + itemPerPage;
	}
	var tableLayout = "";
	for(; i<loops; i++){
		tableLayout += "<tr id='"+data[i].productId+"'>" +
						"<td align='center'>" +
						"<img class='act_icon_edit' src='images/datamanage/edit.png' width='20' height='20' key_id='"+data[i].productId+"' action_goto='EDIT'>&nbsp;&nbsp;" +
						"<img class='act_icon_delete' src='images/datamanage/delete.png' width='20' height='20' key_id='"+data[i].productId+"'></td>" +
						"<td>"+data[i].productName+"</td><td>"+data[i].productDetail+"</td>" +
						"</tr>";
	}
	tableLayout += "</tr><tr class='tr_th'><td colspan='10' align='center'>"+	genNumPageList(pages, totalRecords)+"</td>";
	return tableLayout;
}

function genNumPageList(page, totalRecord){
	var numpageLayout = "";
	var totalPage = 1;
	if(totalRecord > itemPerPage){
		totalPage = Math.ceil((totalRecord / itemPerPage)); 
	}
	for(var i=1; i<=totalPage;i++){
		if(i == page){
			numpageLayout += "<b>"+i+"</b>&nbsp;";
		}else{
			numpageLayout += "<span class='spn_numpage' onclick='gotoPage("+i+")'>"+i+"</span>&nbsp;";
		}
	}
	return numpageLayout;
}

function gotoPage(index){
	var tableLayout = genTable(ProductListData, index);
	$("#dataTbody").html(tableLayout);
}

function getEditData(key_id){
	var action = $("#search_frm").attr('action');
	$.ajax({
		 type: "POST",
		 url: action,
		 data: {
			 productId : key_id,
			 action : "GETEDIT"
			 },
		 dataType: "json",
		 success: function(data){
			 if(data[data.length - 1]){
				 setFieldEdit(data);
			 } else {
				 $("#p_freetext").html('Cannot get item data!');
				 $( "#dialog-message" ).dialog('open');
			 }
		 },
		error : function(xhr, ajaxOptions, thrownError) {
			$("#p_freetext").html('Error while processing '+xhr+" :: "+thrownError);
			 $( "#dialog-message" ).dialog('open');
		}
	});
}

function setFieldEdit(data){
	$("#ins_product_code").val(data[0].productId);
	$("#ins_product_name").val(data[0].productName);
	$("#ins_product_detail").val(data[0].productDetail);
}

